package cn.jbolt.ec.order;

import cn.jbolt.base.JBoltBaseService;
import cn.jbolt.common.model.BecRetailerMemberBalance;
import com.jfinal.kit.Kv;
/**
 * 充值送余额

 */
public class RetailerMemberBalanceService extends JBoltBaseService<BecRetailerMemberBalance> {
    private BecRetailerMemberBalance dao = new BecRetailerMemberBalance().dao();
    @Override
    protected BecRetailerMemberBalance dao(){
        return dao;
    }

    /**
     * 充值
     * @param member_id
     * @param retailer_id
     * @param balance
     * @param bonus
     * @return
     */

    public int charge(int member_id,int retailer_id,int balance,
                    int bonus){

        Kv cond = Kv.by("member_id",member_id).set("retailer_id",retailer_id);

        BecRetailerMemberBalance rec = findFirst(cond);
        if(rec!=null && rec.getId()>0){
            rec.setBalance(balance+rec.getBalance());
            rec.setChargeBonus(bonus+rec.getChargeBonus());
            rec.update();

        }else{
            rec=dao();
            rec.setRetailerId(retailer_id);
            rec.setMemberId(member_id);
            rec.setBalance(balance);
            rec.setChargeBonus(bonus);
            rec.save();

        }

        return rec.getId();
    }

    public int pay(int member_id,int retailer_id,int balance,
                   int bonus){

        Kv cond = Kv.by("member_id",member_id).set("retailer_id",retailer_id);

        BecRetailerMemberBalance rec = findFirst(cond);
        if(rec!=null && rec.getId()>0){
            if((rec.getChargeBonus()<bonus) || (rec.getBalance()<balance)){
                return 2; // 余额不足
            }
            rec.setBalance(rec.getBalance()-balance);
            rec.setChargeBonus(rec.getChargeBonus()-bonus);
            rec.update();


        }else{
           return 1; // 无充值记录

        }

        return 0;
    }

    public BecRetailerMemberBalance get_by_retailer(int member_id,int retailer_id){
        Kv cond = Kv.by("member_id",member_id).set("retailer_id",retailer_id);

        return findFirst(cond);


    }


}
